import log4js from "log4js"
import path from "path"

function getCommonAppender(pathSeg) {
  return {
    type: "dateFile",
    filename: path.resolve(__dirname, "logs", pathSeg, "logging.log"),
    pattern: "yyyy-MM-dd-hh", // 每小时日志滚动
    keepFileExt: true, // 保留文件后缀
    maxLogSize: 1024 * 1024, // 1M
    daysToKeep: 10, // 保留多少份日志
    layout: {
      type: "pattern",
      pattern: "[%d{yyyy-MM-dd hh:mm:ss}] [%p] %c：%m%n"
    }
  }
}

log4js.configure({
  appenders: { // 定义文件的输出方式，sql 日志出口
    sql: getCommonAppender("sql"),
    api: getCommonAppender("api"),
    console: {
      type: 'stdout',
    }

  },
  categories: {
    default: {
      appenders: ["console"],
      level: 'all'
    },
    sql: {
      appenders: ['sql'], // 该分类使用出口sql的配置写入日志
      level: 'all'
    },
    api: {
      appenders: ['api'], // 该分类使用出口sql的配置写入日志
      level: 'all'
    }
  }
})

// 当程序退出时执行,程序关闭那前一刻，程序崩溃的前一刻
process.on("exit", () => {
  console.log(123);
  log4js.shutdown() // 把没有记录完的日志记录完
})

export const sqlLogger = log4js.getLogger("sql")
export const logger = log4js.getLogger()
export const apiLogger = log4js.getLogger("api")

export default logger
